package com.sky.controller.admin;

import com.sky.config.MyImgConfig;
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

@Slf4j
@RestController
@Api(tags = "通用接口")
@RequestMapping("/admin/common")
public class CommonController {


    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.error("文件为空，上传失败！");
        }
//        原始文件名称
        String oldFileName = file.getOriginalFilename();
//        构建新文件名称
        String newFileName = UUID.randomUUID() + "_" + oldFileName;
//        文件请求绝对路径
        String savePath = MyImgConfig.filePath + newFileName;
        log.info("文件请求绝对路径:{}", savePath);
//        保存文件
        File file1 = new File(savePath);
        if (file1.exists()) {
            file1.createNewFile();
        }
        if (file.getSize() != FileCopyUtils.copy(file.getInputStream(), Files.newOutputStream(new File(savePath).toPath()))) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        return Result.success("img/" + newFileName);
    }
}
